package com.wanghua.mall.user.controller;

import java.util.Arrays;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.wanghua.mall.user.exception.PasswordErrorException;
import com.wanghua.mall.user.exception.PhoneExistException;
import com.wanghua.mall.user.exception.UsernameExistException;
import com.wanghua.mall.user.exception.UsernameNotExistException;
import com.wanghua.mall.user.vo.RegisterVo;
import org.springframework.web.bind.annotation.*;

import com.wanghua.mall.user.entity.UserEntity;
import com.wanghua.mall.user.service.UserService;
import com.wanghua.common.utils.PageUtils;
import com.wanghua.common.utils.R;

import javax.annotation.Resource;


/**
 * 用户
 *
 * @author wanghua
 * @email 2367279431@qq.com
 * @date 2021-08-24 18:51:22
 */
@RestController
@RequestMapping("/user/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 第三方账号登录->>Gitee
     */
    @PostMapping("/giteeLogin")
    public R giteeLogin(@RequestBody String giteeUserVoJson) {
        UserEntity userEntity = userService.giteeLogin(giteeUserVoJson);
        return R.ok().put("data", JSON.toJSONString(userEntity));
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public R register(@RequestBody RegisterVo registerVo) {
        try {
            userService.register(registerVo);
            return R.ok();
        } catch (PhoneExistException | UsernameExistException e) {
            //TODO 待完善返回信息
            return R.error().put("msg", e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public R login(@RequestBody RegisterVo registerVo) {
        try {
            UserEntity userEntity = userService.login(registerVo);
            return R.ok().put("data", JSON.toJSONString(userEntity));
        } catch (UsernameNotExistException | PasswordErrorException e) {
            return R.error().put("msg", e.getMessage());
        }
    }

    /**
     * 列表
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = userService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        UserEntity user = userService.getById(id);
        return R.ok().put("user", user);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody UserEntity user) {
        userService.save(user);
        return R.ok();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public R update(@RequestBody UserEntity user) {
        userService.updateById(user);
        return R.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        userService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

}
